<template>
  <nav class="top-navbar" :class="{ fixed: isSticky }">
    <div class="back">&lt;</div>
    <div class="nav-right">
      <a href="/main/home" class="nav-link">首页</a>
      <a href="/main/profile" class="nav-link">个人中心</a>
      <a href="/main/cart" class="nav-link">购物车</a>
      <a href="/main/favorite" class="nav-link">收藏夹</a>
      <a href="#" class="nav-link">帮助中心</a>
      <!-- 动态切换按钮 -->
      <div v-if="!userStore.isLoggedIn">
        <a href="/login" class="nav-link">登录/注册</a>
      </div>
      <div v-else>
        <button @click="logout" class="sign-out-button">退出</button>
      </div>
    </div>
  </nav>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/userStore";

const userStore = useUserStore();
const router = useRouter();
const isSticky = ref(false); // 定义 isSticky 状态

// 监听滚动事件
const handleScroll = () => {
  isSticky.value = window.pageYOffset > 50; // 滚动超过50px时应用fixed样式
};

onMounted(() => {
  window.addEventListener("scroll", handleScroll);
});

onBeforeUnmount(() => {
  window.removeEventListener("scroll", handleScroll);
});

const logout = () => {
  userStore.clearUser();
  router.push("/main/home");
};
</script>

<style scoped>
.top-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #E05649;
  padding: 10px 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 20px;
  /* 控制链接之间的间距 */
}

.nav-link:hover {
  color: rgb(130, 69, 25);
  border-radius: 20%;
}

.nav-link {
  margin-left: 20px;
  text-decoration: none;
  color: rgb(255, 255, 255);
}

.sign-in-button,
.register-button,
.sign-out-button {
  background-color: #e05649;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
}
</style>